package com.xinchao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.xinchao.core.constant.BusinessConstant;
import com.xinchao.core.constant.ModuleConstant;
import com.xinchao.dao.AsstRouteMapper;
import com.xinchao.dao.AsstTravelRecordMapper;
import com.xinchao.dao.UserMapper;
import com.xinchao.model.AsstRoute;
import com.xinchao.model.AsstTravelRecord;
import com.xinchao.model.OperationLog;
import com.xinchao.model.User;
import com.xinchao.model.dto.RouteInfoDTO;
import com.xinchao.model.page.PageInfo;
import com.xinchao.service.AsstService;
import com.xinchao.service.OperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xp630
 * @Date: 2018/9/25 16:21
 */
@Service
public class AsstServiceImpl implements AsstService {

    @Autowired
    private AsstRouteMapper asstRouteMapper;
    @Autowired
    private AsstTravelRecordMapper asstTravelRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OperationLogService operationLogService;

    public static final String BIND_ROUTE_ERROR="用户绑定线路失败";

    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public void bindUserRoutes(Long userId, List<Long> routeList,String cityCode){
        //合法性验证
        if (userId == null || userId==0){
            return;
        }
        //删除之前绑定的线路
        asstTravelRecordMapper.deleteByUser(userId);
        //开始批量insert
        if(routeList==null || routeList.isEmpty()){
            return ;
        }
        //组装用户路线关系对象
        List<AsstTravelRecord> records = new ArrayList<>();
        for(Long routeId:routeList){
            AsstTravelRecord record = new AsstTravelRecord();
            record.setRouteId(routeId);
            record.setUserId(userId);
            record.setAddTime(System.currentTimeMillis());
            record.setCityCode(cityCode);
            records.add(record);
        }
        //批量插入数据
        asstTravelRecordMapper.batchInsert(records);
    }

    /**
     * 绑定路线用户关系
     * @param routeId 路线id
     * @param userList 用户id列表
     * @param cityCode 城市编码
     * @param loginUser 当前登录用户
     * @param remortIP 当前登录Ip
     */
    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public void bindRouteUsers(Long routeId, List<Long> userList, String cityCode, User loginUser, String remortIP){
        //合法性验证
        if (routeId == null || routeId==0){
            return;
        }
        //验证城市是否为空
        if(cityCode == null || cityCode.trim().equalsIgnoreCase("")){
            return;
        }
        // 删除之前绑定的线路
        asstTravelRecordMapper.deleteByRoute(routeId,cityCode);
        //开始批量insert
        if(userList==null || userList.isEmpty()){
            return ;
        }
        //组装用户路线关系对象
        List<AsstTravelRecord> records = new ArrayList<>();
        for(Long userId:userList){
            AsstTravelRecord record = new AsstTravelRecord();
            record.setRouteId(routeId);
            record.setUserId(userId);
            record.setAddTime(System.currentTimeMillis());
            record.setCityCode(cityCode);
            records.add(record);
        }
        // 批量插入数据
        asstTravelRecordMapper.batchInsert(records);

        // 保存操作日志
        StringBuilder userNameSb = new StringBuilder();
        for(Long userId: userList) {
            User user = userMapper.getUserById(userId);
            if(user != null) {
                userNameSb.append(","+user.getRealname());
            }
        }
        String userNameStr = userNameSb.toString();
        if(userNameStr.length() > 1) {
            userNameStr = userNameStr.substring(1);
        }
        AsstRoute route = asstRouteMapper.getRouteByRouteVersion(routeId, cityCode);
        StringBuilder routeNameSb = new StringBuilder();
        if(route != null) {
            routeNameSb.append(route.getRouteName());
        }
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationContent("路线：" + routeNameSb + "绑定用户：" + userNameStr);
        operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        operationLog.setOperationModule(ModuleConstant.MODULE_ASSTROUTE_MNG);
        operationLog.setRealname(loginUser.getRealname());
        operationLog.setUserName(loginUser.getUserName());
        operationLog.setOperationIp(remortIP);
        operationLogService.saveOperationLog(operationLog);
    }

    @Override
    @Transactional(readOnly = true)
    public List<AsstRoute> getRouteListByCity(String cityCode) {
        if(cityCode==null || ("").equals(cityCode.trim())){
            return new ArrayList<AsstRoute>();
        }
        return  asstRouteMapper.getRouteByCity(cityCode);
    }

    @Override
    public List<AsstTravelRecord> getUserRouteRecords(Long userId) {
        return asstTravelRecordMapper.selectByUserId(userId);
    }

    @Override
    public PageInfo<RouteInfoDTO> listByPage(String routeName, String userName, String cityCode,Integer pageNum,Integer pageSize){
        Page page = PageHelper.startPage(pageNum, pageSize,true);
        List<RouteInfoDTO> dataList =asstTravelRecordMapper.getRouteInfoList(routeName,userName,cityCode);
        if (page == null) {
            return new PageInfo<>(pageNum, pageSize, 0, Lists.newArrayList());
        }
        PageInfo<RouteInfoDTO> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setList(dataList);
        return pageInfo;
    }
}
